<template>
    <a-upload
            v-model:file-list="fileList"
            name="file"
            list-type="picture-card"
            :show-upload-list="false"
            :action="uploadUrl"
            :disabled="uploadDisabled"
            :before-upload="beforeUpload"
            @change="handleChange"
    >
        <a-image v-if="imgUrl" :src="imgUrl" alt="avatar"
             style="width: 100px;height: 100px;"/>
        <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
        </div>
    </a-upload>
</template>

<script>
    import {ref,onMounted} from "vue";
    import {message} from "ant-design-vue";
    import {DownOutlined, LoadingOutlined, PlusOutlined} from "@ant-design/icons-vue";

    export default {
        name: "upload",
        components: {
            DownOutlined,
            LoadingOutlined,
            PlusOutlined,
        },
        props:{
            imgUrl: {
                required: false
            },
            uploadUrl:{
                required: true
            },
            uploadDisabled:{
                required: false,
            }
        },
        setup(props,context){

            const fileList = ref([]);
            const loading = ref(false);

            const handleChange = info => {
                if (info.file.status === 'uploading') {
                    console.log("上传uploading信息：", info)
                    loading.value = true;
                    return;
                }
                if (info.file.status === 'done') {
                    console.log("上传done信息：", info)
                    context.emit('update:imgUrl', info.file.response)
                    loading.value = false
                }
                if (info.file.status === 'error') {
                    console.log("上传error信息：", info)
                    loading.value = false;
                    message.error('upload error');
                }
            };

            const beforeUpload = file => {
                const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                    message.error('You can only upload JPG file!');
                }
                const isLt5M = file.size / 1024 / 1024 < 5;
                if (!isLt5M) {
                    message.error('Image must smaller than 5MB!');
                }
                return isJpgOrPng && isLt5M;
            };

            return {
                fileList,
                loading,
                handleChange,
                beforeUpload
            }
        }
    }
</script>

<style scoped>

</style>